import os
from typing import Optional
from datetime import datetime
from ..utils.file_utils import ensure_dir_exists

class FileGenerator:
    """基础Markdown文件生成器"""
    
    @staticmethod
    def generate_from_content(
        content: str,
        output_path: str,
        mode: str = 'w',
        encoding: str = 'utf-8'
    ) -> bool:
        """
        将内容写入Markdown文件
        :param content: Markdown格式内容
        :param output_path: 输出文件路径
        :param mode: 写入模式（默认覆盖）
        :param encoding: 文件编码
        """
        try:
            ensure_dir_exists(os.path.dirname(output_path))
            with open(output_path, mode, encoding=encoding) as f:
                f.write(content)
            return True
        except Exception as e:
            print(f"文件生成失败: {e}")
            return False

    @staticmethod
    def generate_file_structure(
        root_dir: str,
        output_file: str = "STRUCTURE.md",
        ignore_dirs: Optional[list] = None,
        depth: int = 0
    ) -> str:
        """
        生成目录树结构的Markdown[2](@ref)
        :param root_dir: 要扫描的根目录
        :param output_file: 输出文件名
        :param ignore_dirs: 忽略的目录列表
        :param depth: 递归深度（内部使用）
        """
        ignore_dirs = ignore_dirs or ['.git', '__pycache__', 'node_modules']
        structure = ""
        
        if os.path.isdir(root_dir):
            basename = os.path.basename(root_dir)
            structure += f"{'  ' * depth}- **{basename}/**\n"
            
            for name in sorted(os.listdir(root_dir)):
                if name in ignore_dirs:
                    continue
                    
                full_path = os.path.join(root_dir, name)
                if os.path.isdir(full_path):
                    structure += FileGenerator.generate_file_structure(
                        full_path, None, ignore_dirs, depth + 1
                    )
                else:
                    structure += f"{'  ' * (depth + 1)}- {name}\n"
        
        if output_file:
            FileGenerator.generate_from_content(
                f"# 项目结构\n\n{structure}",
                os.path.join(root_dir, output_file)
            )
        
        return structure